/*
 * @Author: yangzonglong
 * @Date: 2021-02-25 14:35:42
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: TLL
 * @LastEditTime: 2021-05-06 11:08:44
 * @Auditor: 
 */
import React, { useCallback, useState, memo, useEffect } from 'react';
import { Input, AutoComplete } from 'antd';
import { AutoCompleteProps } from './interface';
import { getData } from './Api';
import { setExtra } from '../formx/util';
import Material from '../materiel/Materiel';
import { Icon } from '@library';

const autoComplete: React.FC<AutoCompleteProps> = (props) => {

  const { onChange, fieldNames: propFieldNames, dataSource: appoint, ...selectProps } = props;

  const [options, setOptions] = useState<{ value: string }[]>([]);
  const [visible, setIsVisible] = useState(false);
  const [value, setValue] = useState('');

  useEffect(() => {
    if(props.value) setValue(props.value);
  }, [props.value]);
  
  const _onSelect = useCallback(value => {
    setValue(value);
    if(options?.length) {
      const list = options.filter((ele: any) => ele.materialCode === value);
      if(list?.length === 1) setExtra({ '_materialCode': list });
    }
    onChange(value, "materialCode");
  }, [onChange, options]);
  
  const onSearch = useCallback(async (searchText: string) => {
    const result = await getData(searchText);
    result?.rows?.forEach((ele: any) => ele.value = ele.materialCode);
    setOptions(result?.rows);
  }, []) 

  const showModal = useCallback(() => setIsVisible(true), [])

  const onCancel = useCallback(() => setIsVisible(false), [])

  const onOk = useCallback((item: any) => {
    setValue(item?.[0].materialCode);
    setExtra({ '_materialCode': item });
    onChange(item?.[0].materialCode, "materialCode");
    setIsVisible(false);
  }, [])

  return (
    <div>
      <AutoComplete
        {...selectProps}
        value={value}
        options={options}
        onSearch={onSearch}
        onSelect={_onSelect}
      >
        <Input suffix={<Icon icon="&#xe63b;" onClick={showModal} />} />
      </AutoComplete>
      <Material selectionType="radio" visible={visible} onCancel={onCancel} onOk={onOk} />
      {/* <ModalTableInModel moduleName="material" modelName="Material" visible={visible} onCancel={onCancel} onOk={onOk} /> */}
    </div>
  )
}

export default memo(autoComplete)
